<template>
  <VGroup>
    <el-select
      style="width: 100%"
      v-model="sitesVal"
      clearable
      filterable
      placeholder="请选择平台"
      :multiple="multiple"
      @change="handleChangeSite"
    >
      <el-option
        v-for="item in sites"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-select
      style="width: 100%"
      v-model="shopVal"
      clearable
      filterable
      placeholder="请选择店铺"
      :multiple="multiple"
    >
      <el-option
        v-for="item in shop"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </VGroup>
</template>

<script setup>
import { getSites, getShop } from '@/api/public'

const props = defineProps({
  platform: { type: [String, Number], default: '' },
  modelValue: { type: [String, Number, Array], default: '' },
  multiple: { type: Boolean, default: false },
  autoLoad: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'change'])

const sites = ref([])
const sitesVal = ref()
const shop = ref([])
const shopVal = ref()

onMounted(() => {
  if (props.autoLoad) getSitesReq()
})

watch(
  () => props.modelValue,
  val => {}
)

watch(
  () => props.platform,
  () => {
    getSitesReq()
  }
)

watch(
  () => [sitesVal.value, shopVal.value],
  val => {
    const [siteId, shopId] = val

    if (!siteId || !shopId) {
      emit('update:modelValue', undefined)
      return
    }
    emit('update:modelValue', { siteId, shopId })
  }
)

const getSitesReq = async () => {
  const { platform } = props
  try {
    sitesVal.value = ''
    const { data } = await getSites({ platform_ids: [platform] })
    sites.value = data.map(n => ({
      label: n.site_name,
      value: n.site_id,
    }))
  } catch (e) {
    console.error(e)
  }
}

const handleChangeSite = e => {
  getShopReq(e)
}

const getShopReq = async ids => {
  try {
    shopVal.value = ''
    const { data } = await getShop({ site_ids: [ids] })
    shop.value = data.map(n => ({
      label: n.shop_name,
      value: n.shop_id,
    }))
  } catch (e) {
    console.error(e)
  }
}
</script>
